@file:Suppress("DEPRECATION")

package com.jerry.usbserial.fragment.udp

import android.annotation.SuppressLint
import android.app.AlertDialog
import android.app.Dialog
import android.app.ProgressDialog
import android.content.Context
import android.os.Bundle
import android.view.View
import com.jerry.usbserial.R
import com.jerry.usbserial.adapter.MenuAdapter
import com.jerry.usbserial.util.*
import com.jerry.usbserial.util.task.udp.UDPMenuTask
import kotlinx.android.synthetic.main.bar_common.*
import kotlinx.android.synthetic.main.frg_menu_edit.*
import kotlinx.android.synthetic.main.item_menu_header.*

class UdpMenuFragment : UdpFragment() {
    private lateinit var menuAdapter: MenuAdapter

    override val layoutId: Int = R.layout.frg_menu_edit

    private var ipAddress: String? = null

    @SuppressLint("SetTextI18n")
    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        toolbar_title.text = "WIFI编辑菜单"
        toolbar.inflateMenu(R.menu.menu_update)
        toolbar.setOnMenuItemClickListener {
            if (it.itemId == R.id.update) {
                getMenuItemList()
                return@setOnMenuItemClickListener true
            }
            if (it.itemId == R.id.add) {
                menuAdapter.addMenu()
                return@setOnMenuItemClickListener true
            }
            return@setOnMenuItemClickListener false
        }

        select_all.setOnCheckedChangeListener { cb, b ->
            if (cb.isPressed) menuAdapter.chooseAll(b)
        }

        menuAdapter = MenuAdapter(activity as Context)
        val json = mContext.getSp().getString("menu_data", null)
        json?.let {
            menuAdapter.updateMenu(it.jsonToList())
        }
        menuAdapter.setOnSelectedChanged {
            select_all.isChecked = menuAdapter.isChosenAll()
        }
        select_all.isChecked = menuAdapter.isChosenAll()
        listView.adapter = menuAdapter

        bt_update.isEnabled = true
        bt_update.text = "更新菜单"
        bt_update.setOnClickListener {
            val waitSendList = menuAdapter.getDataByChecked() ?: return@setOnClickListener

            if (ipAddress.isNullOrEmpty()) {
                mContext.showToast("无法获取手机 IP 地址")
                return@setOnClickListener
            }

            AlertDialog.Builder(mContext)
                .setTitle("提示")
                .setMessage("确认手机和设备已连接同一 WiFi!")
                .setCancelable(false)
                .setPositiveButton("更新") { _, _ -> startTask(waitSendList) }
                .setNegativeButton(android.R.string.cancel, null)
                .show()
        }
    }

    private fun startTask(waitSendList: List<MenuItem>) {
        ProgressDialog(mContext).apply {
            setMessage("菜单更新中...")
            setCancelable(false)
            setCanceledOnTouchOutside(false)
            max = 100
            setProgressStyle(ProgressDialog.STYLE_HORIZONTAL)
            isIndeterminate = false
            val udpTask = UDPMenuTask(ipAddress!!, waitSendList).apply {
                setOnProcessListener {
                    progress = it
                }
                setOnResultListener {
                    dismiss()
                    activity?.runOnUiThread { mContext.showToast(it) }
                }
                start()
            }
            setButton(Dialog.BUTTON_NEGATIVE, context.getString(android.R.string.cancel)) { _, _ ->
                udpTask.cancel()
                mContext.showToast("菜单更新未完成!")
            }
            show()
        }
    }

    override fun handlerResult(ssid: String?, bssid: String?, ip: String?, error: String?) {
        ipAddress = ip
    }

    private fun getMenuItemList() {
        RemoteRepo.getApi().menuItemList().applySchedulers(this)
            .subscribe(object : ResultObserver<List<MenuItem>>() {
                override fun handlerSuccess(data: List<MenuItem>) {
                    if (data.isNotEmpty()) {
                        menuAdapter.updateMenu(data)
                    }
                }

                override fun handlerError(code: Int, msg: String) {
                    mContext.showToast("数据获取失败")
                }
            })
    }

}